import { defineStore } from 'pinia';
import type { UserState } from './types/type';
import { SET_TOKEN, GET_TOKEN } from '@/utils/token';
import { constantRoute } from '@/router/routes';
import { getUserInfo, getMenuAuthorityList } from '@/api/user';
import { ElMessage } from 'element-plus';
import { RouteRecordRaw } from 'vue-router';

// 定义菜单项接口
interface MenuItem {
    path: string;
    name: string;
    component: any;
    meta?: {
        title: string;
        hidden: boolean;
        icon: string;
        requiresAuth?: boolean;
    };
    children?: MenuItem[];
}

// 定义 componentMap
const componentMap = {
};

// 创建用户小仓库
let useUserStore = defineStore('User', {
    state: (): UserState => {
        return {
            token: GET_TOKEN(),
            isHead: false,
            isExamine: false,
            userPurview: null,
            authorityId: "",
            userInfo: {
                menuRoutes: [] as any,
                uuid: '',
                userName: '',
                nickName: '',
                headerImg: '',
                sideMode: '',
                baseColor: '',
                activeColor: '',
                authorityId: 0,
                ID: 1,
            }
        };
    },
    actions: {
        // 初始化用户信息
        initUseInfo() {
            this.token = GET_TOKEN();
            this.userInfo.menuRoutes = [];
            this.userInfo.uuid = '';
            this.userInfo.userName = '';
            this.userInfo.nickName = '';
            this.userInfo.headerImg = '';
            this.userInfo.sideMode = '';
            this.userInfo.baseColor = '';
            this.userInfo.activeColor = '';
            this.userInfo.authorityId = 0;
            this.userInfo.ID = 1;
        },

        // 保存token
        saveToken(data: string) {
            this.token = data;
            SET_TOKEN(this.token);
        },

        // 退出登录
        delToken() {
            SET_TOKEN("");
            this.token = GET_TOKEN();
            localStorage.clear();
            this.initUseInfo();
            ElMessage.success("退出成功！");
        },

        // 获取用户信息
        async getUseInfo() {
            const resData = await getUserInfo().then((res) => {
                return res.data;
            });
            if (resData.code === 7) {
                ElMessage.error("获取用户信息失败！");
                return;
            } else {
                this.userInfo.nickName = resData.data.nickName;
                this.userInfo.uuid = resData.data.uuid;
                this.userInfo.headerImg = resData.data.headerImg;
                this.userInfo.userName = resData.data.userName;
                this.userInfo.sideMode = resData.data.sideMode;
                this.userInfo.baseColor = resData.data.baseColor;
                this.userInfo.activeColor = resData.data.activeColor;
                this.userInfo.authorityId = resData.data.authorityId;
                this.userInfo.ID = resData.data.ID;

                // 判断是否为审核人
                this.isExamine = this.userInfo.authorityId === 333;

                // 判断是否为技术负责人
                this.isHead = this.userInfo.authorityId === 777;
                localStorage.setItem("isHead", this.isHead ? "true" : "false");
            }
        },

        // 获取菜单权限列表
        async getMenuAuthorityList() {
            const { data } = await getMenuAuthorityList();
            if (data.code === 7) {
                ElMessage.error("获取用户信息失败！");
                return;
            } else {
                const processedMenus = this.processMenus(data.data.menus as MenuItem[]);
                this.userInfo.menuRoutes = processedMenus;
                return data.data.menus;
            }
        },

        // 处理菜单数据
        processMenus(menus: MenuItem[]): RouteRecordRaw[] {
            return menus.map((menu: MenuItem): RouteRecordRaw => {
                const component = componentMap[menu.path as keyof typeof componentMap];
        
                // 动态构建对象
                const route: Partial<RouteRecordRaw> = {
                    path: menu.path,
                    name: menu.name,
                    component, // 使用 componentMap
                    meta: menu.meta || {
                        title: '',
                        hidden: false,
                        icon: '',
                        requiresAuth: false,
                    },
                };
        
                // 如果 children 存在且不为空数组，则添加 children 字段
                if (menu.children && menu.children.length > 0) {
                    route.children = this.processMenus(menu.children) as RouteRecordRaw[];
                }
        
                // 返回完整的 RouteRecordRaw 对象
                return route as RouteRecordRaw;
            });
        }
    },
    getters: {
        // 计算属性...
    }
});

export default useUserStore;